package com.security.zhl.order.biz.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.security.zhl.order.biz.model.UserDTO;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String token = request.getHeader("json-token");
        if (token !=null ){
            JSONObject userJson = JSON.parseObject( token );
            UserDTO tUser = new UserDTO();
            tUser.setUsername( userJson.getString("principal") );
            JSONArray authoritiesArry = userJson.getJSONArray("authorities");
            String[] authorities = authoritiesArry.toArray( new String[authoritiesArry.size()]);
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(tUser , null , AuthorityUtils.createAuthorityList(authorities));
            authenticationToken.setDetails( new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication( authenticationToken );
        }
        filterChain.doFilter( request , response );
    }
}
